// pages/food/fd.js
const cabinBarWidth = 200;
const app = getApp();
const call = require('../../utils/request.js');
const cabin = require('../../utils/cabin.js');
const util = require('../../utils/util.js');
Page({
  data: {
    tabs: [{
      cabinName: '冷藏室',
      cabinId: 1
    }],
    sliderLeft: 0,
    activeCabin: 0,
    foodBody: [],
    foodList: [],
    windowHeight: 0,
    stDelete: false,
    delList: [],
    loading: true,
    openFood: ''
  },
  onRecipe() {
    wx.navigateTo({
      url: '/pages/foodmanager/recipe/recipe',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideLoading() //隐藏加载框
    var that = this;
    wx.getSystemInfo({
      success(res) {
        that.setData({
          windowHeight: res.windowHeight
        });
      }
    });
  },
  onShow(){
    this._PermissionCheck()
  },
  tapCabin(e) {
    const {
      activeView,
      cabinId
    } = e.currentTarget.dataset;
    app.globalData.foodmanager.activeCabin = this.data.tabs[activeView].cabinName
    this.setData({
      sliderLeft: activeView * cabinBarWidth,
      activeCabin: activeView,
      foodList: this.data.foodBody.filter(i => i.location === cabinId)
    });
  },
  getCabin() {
    let storageTabs = [{
      cabinName: '冷藏室',
      cabinId: 1
    }, {
      cabinName: '冷冻室',
      cabinId: 12
    }];;
    let tabs = [{
      cabinName: '全舱室',
      cabinId: -1
    }, {
      cabinName: '冷藏室',
      cabinId: 1
    }, {
      cabinName: '冷冻室',
      cabinId: 12
    }];

    const url = `/service/fridge/cabin/getByDeviceId?deviceId=${app.globalData.mac}`;
    call.postData(url, {}, res => {
      console.log('_getByDeviceId_success', res)
      if (res.data.length !== 0) {
        storageTabs = res.data.map(cb => {
          return {
            cabinName: cabin.cabins.find(i => i.cabinId == cb).cabinName,
            cabinId: cb
          }
        });
        tabs = storageTabs;
        tabs.unshift({
          cabinName: '全舱室',
          cabinId: -1
        })
      }
      wx.setStorage({
        key: 'cabins',
        data: storageTabs
      })
      this.setData({
        tabs: tabs
      })

    }, res => {
      console.log('获取舱室列表失败', res);
      wx.showToast({
        title: '网络好像出小差了_getByDeviceId',
        icon: 'none'
      })
    })
  },
  // 获取指定舱室的食材，location为舱室id
  _getFood(location) {
    const url = `/service/v1/food/getList?access_token=${app.globalData.access_token}`;
    const data = {
      "deviceId": app.globalData.mac,
      "location": location
    };
    //调用服务
    call.postData(url, data, res => {
      if (res.data) {
        res.data.map(i => {
          i.percent = util.figTime(i.shelfLife, i.dateOfProduct).percent,
            i.overDueTime = util.figTime(i.shelfLife, i.dateOfProduct).overDueTime,
            i.proDate = util.fomatDate(new Date(i.dateOfProduct))
        })
        res.data.sort(util.compareList('overDueTime'));
        //默认显示全舱室
        this.setData({
          foodBody: res.data,
          sliderLeft: 0,
          activeCabin: 0,
          foodList: res.data,
          loading: false
        });
      } else {
        wx.showToast({
          title: '网络好像出小差了',
          icon: 'none'
        })
      }
    }, res => {
      console.log('获取食材列表失败', res);
      wx.showToast({
        title: '网络好像出小差了_getList',
        icon: 'none'
      })
    });
  },
  // 添加食材
  onAdd: function() {
    wx.navigateTo({
      url: './add/add'
    })
  },
  //删除开关
  onToggleDel() {
    this.setData({
      stDelete: !this.data.stDelete,
      delList: []
    })
  },
  tapFood(e) {
    let list = this.data.delList.slice();
    const createTime = e.currentTarget.dataset.createTime;
    if (this.data.stDelete) { //添加食材进入删除列表
      if (this.data.delList.indexOf(createTime) > -1) { //已有
        list = list.filter(i => i !== createTime)
      } else { //新增
        list.push(createTime);
      }
      this.setData({
        delList: list
      })
    } else { //打开单个食材
      list.push(createTime);
      this.setData({
        openFood: e.currentTarget.dataset,
        delList: list
      });
    }
  },
  closeCover() {
    this.setData({
      openFood: '',
      delList: []
    })
  },
  onDel() {
    var that = this;
    let toast;
    if (this.data.delList.length === 0) {
      wx.showToast({
        title: '请选择需要删除的食材!',
        icon: 'none',
        duration: 2000
      })
    } else {
      wx.showModal({
        title: '确认删除',
        content: '确认移除食材么？',
        success(res) {
          if (res.confirm) { //用户点击确定
            wx.showLoading({
              title: '正在操作，请稍后...',
            })
            const delFridgeFoods = that.data.delList.map(i => {
              return {
                createTime: i
              }
            });
            const url = `/service/v1/food/batchFridgeFoods?access_token=${app.globalData.access_token}`;
            const params = {
              deviceId: app.globalData.mac,
              delFridgeFoods: delFridgeFoods
            };
            call.postData(url, params,
              res => {
                that._getFood(-1); //更新食材信息
                wx.hideLoading(); //隐藏加载
                toast = '已删除';
                that.setData({
                  stDelete: false,
                  openFood: '',
                  delList: []
                })
              },
              err => {
                toast = '删除食材失败';
              });
            wx.showToast({
              title: toast,
              icon: 'fail',
              duration: 2000
            });
          }
        }
      })

    }

  },
  _PermissionCheck() {
    if (app.globalData.mac && app.globalData.access_token) {
      this.getCabin();
      app.globalData.foodmanager.activeCabin = '冷藏室'
      this._getFood(-1); //获取所有舱室食材
    } else {
      app._getMac().then(i => {
        if (i != '') {
          this.getCabin();
          app.globalData.foodmanager.activeCabin = '冷藏室'
          this._getFood(-1); //获取所有舱室食材
        }
      })
    }
  }
})